package cn.zyjw.controller;

import cn.zyjw.domain.SysPrivilege;
import cn.zyjw.model.R;
import cn.zyjw.service.SysPrivilegeService;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api(value = "权限管理接口")
@RequestMapping("/privileges")
public class SysPrivilegeController {

    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    @GetMapping
    @ApiOperation("分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页展示条数")
    })
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    public R<Page<SysPrivilege>> findByPage(@ApiIgnore Page<SysPrivilege> page) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> sysPrivilegePage = sysPrivilegeService.page(page);
        return R.ok(sysPrivilegePage);
    }

    @PostMapping
    @ApiOperation("新增功能权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "sysPrivilege Json对象")
    })
    @PreAuthorize("hasAuthority('sys_privilege_create')")
    public R<String> add(@RequestBody @Validated SysPrivilege sysPrivilege) {
        boolean save = sysPrivilegeService.save(sysPrivilege);
        if (save) {
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }

    @PatchMapping
    @ApiOperation("编辑功能权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "sysPrivilege json 对象")
    })
    public R upd(@RequestBody @Validated SysPrivilege sysPrivilege) {
        boolean b = sysPrivilegeService.updateById(sysPrivilege);
        if (b) {
            return R.ok("修改成功");
        }
        return R.fail("修改失败");
    }

}
